package com.shimao.celnet.payment.controller.apinotcheck;


import com.baiwang.bop.client.BopException;
import com.baiwang.bop.client.IBopClient;
import com.baiwang.bop.request.impl.invoice.impl.InvoicePrintRequest;
import com.baiwang.bop.respose.entity.InvoicePrintResponse;
import com.shimao.celnet.payment.form.IAppInterfaceForm;
import com.shimao.celnet.payment.model.PInvoiceBlue;
import com.shimao.celnet.payment.model.PInvoiceRed;
import com.shimao.celnet.payment.model.request.CallIn_InvoicePrintRequest;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.IAppInterfaceService;
import com.shimao.celnet.payment.service.PInvoiceBlueService;
import com.shimao.celnet.payment.service.PInvoiceRedService;
import com.shimao.celnet.payment.service.apiservice.CallOut_invOpenOutService;
import com.shimao.celnet.payment.util.MyDateUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @Author: christ
 * @Description: 发票打印接口;外部系统--》支付平台
 */

@RestController
@RequestMapping(value = "/invoice")
public class CallOut_invPrintOutController {

    protected Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private CallOut_invOpenOutService invOpenOutService;
    @Autowired
    private PInvoiceBlueService pInvoiceBlueService;
    @Autowired
    private PInvoiceRedService pInvoiceRedService;
    @Autowired
    private CallOut_invPrintRetInfoOutController callOut_invPrintRetInfoOutController;
    //接口应用注册Service
    @Autowired
    public IAppInterfaceService iAppInterfaceService;
    @RequestMapping(value = "/print", method = {RequestMethod.POST, RequestMethod.GET})
    public Object printInvoice(@RequestBody @Valid CallIn_InvoicePrintRequest InvoicePrintRequest, BindingResult result) {
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        //界面输入验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson;
            }
        }
        //声明变量
        String invoiceGuid = InvoicePrintRequest.getInvoiceGuid();//记录guid
        String invoiceType = InvoicePrintRequest.getBlueRedType();//发票类型
        PInvoiceBlue pInvoiceBlue = null;
        PInvoiceRed pInvoiceRed = null;
        String date = "";//当前时间转换
        //因为打印是没有通过接口请求的，而是url的get方式进入一个页面，通过页面的ajax的异步post请求这个接口
        String PappKey = "";
        String PinterfaceId = "";
        try {
            String token = invOpenOutService.getToken();
            IBopClient client = invOpenOutService.getClient();
            InvoicePrintRequest request = new InvoicePrintRequest();

            if ("blue".equalsIgnoreCase(invoiceType)) {

                pInvoiceBlue = pInvoiceBlueService.getByKey(invoiceGuid);
                //获取记录id的appkey和interfaceId
                PappKey = pInvoiceBlue.getAppKey();
                PinterfaceId = pInvoiceBlue.getInterfaceId();
                //纳税人识别号,设备类型,发票种类编码,开票点编码,发票代码，发票号码都可以通过数据库中查询到
                request.setSellerTaxNo(pInvoiceBlue.getSellerTaxNo());//纳税人识别号--20
                request.setDeviceType(pInvoiceBlue.getDeviceType());//设备类型 0税控服务器，1税控盘
                request.setInvoiceTypeCode(pInvoiceBlue.getInvoiceTypeCode());//发票种类编码 004:增值税专用发票，007:增值税普通发票，025：增值税卷式发票
                request.setInvoiceTerminalCode(pInvoiceBlue.getInvoiceYerminalCode());//开票点编码
                request.setInvoiceCode(pInvoiceBlue.getInvoiceCode());//发票代码
                request.setInvoiceNo(pInvoiceBlue.getInvoiceNo());//发票号码
                //打印类型，打印方式，最好是在界面进行选择
                request.setInvoicePrintType(InvoicePrintRequest.getInvoicePrintType());//打印类型 0：发票打印，1：清单打印
                //打印方式 0：每次点击都弹出打印设置框 1：只在第一次点击时弹出打印设置框。默认为1;
                //填写0的时候报错
                request.setInvoicePrintMode("1");
            } else if ("red".equalsIgnoreCase(invoiceType)) {
                pInvoiceRed = pInvoiceRedService.getByKey(invoiceGuid);
                PappKey = pInvoiceRed.getAppKey();
                PinterfaceId = pInvoiceRed.getInterfaceId();
                //纳税人识别号,设备类型,发票种类编码,开票点编码,发票代码，发票号码都可以通过数据库中查询到
                request.setSellerTaxNo(pInvoiceRed.getSellerTaxNo());//纳税人识别号--20
                request.setDeviceType(pInvoiceRed.getDeviceType());//设备类型 0税控服务器，1税控盘
                request.setInvoiceTypeCode(pInvoiceRed.getInvoiceTypeCode());//发票种类编码 004:增值税专用发票，007:增值税普通发票，026：增值税电子发票，025：增值税卷式发票
                request.setInvoiceTerminalCode(pInvoiceRed.getInvoiceYerminalCode());//开票点编码
                request.setInvoiceCode(pInvoiceRed.getInvoiceCode());//发票代码
                request.setInvoiceNo(pInvoiceRed.getInvoiceNo());//发票号码
                //打印类型，打印方式，最好是在界面进行选择
                request.setInvoicePrintType(InvoicePrintRequest.getInvoicePrintType());//打印类型 0：发票打印，1：清单打印
                //打印方式 0：每次点击都弹出打印设置框 1：只在第一次点击时弹出打印设置框。默认为1
                request.setInvoicePrintMode("1");
            }
            InvoicePrintResponse response = client.execute(request, token, InvoicePrintResponse.class);
            //打印成功后，需要更新打印状态和打印时间
            if ("blue".equalsIgnoreCase(invoiceType)) {
                pInvoiceBlue.setInvoicePrintFlg("1");
                date = MyDateUtil.DateToStr(new Date(), MyDateUtil.formatDefaultTimestamp);
                pInvoiceBlue.setInvoicePrintTime(date);
                pInvoiceBlueService.update(pInvoiceBlue);
            }
            if ("red".equalsIgnoreCase(invoiceType)) {
                pInvoiceRed.setInvoicePrintFlg("1");
                date = MyDateUtil.DateToStr(new Date(), MyDateUtil.formatDefaultTimestamp);
                pInvoiceBlue.setInvoicePrintTime(date);
                pInvoiceRedService.update(pInvoiceRed);
            }
            retJson.addBody("print", response.toString());
            //============1,根据app_key和interface_id查询出i_app_interface表的guid====
            IAppInterfaceForm iAppInterfaceForm = iAppInterfaceService.getInfoByAppIfKey(PappKey, PinterfaceId);
            //============2，根据guid，查询i_app_interface_asyn表所有需要回调的系统的returnUrl====
            List<IAppInterfaceForm> iAppInterfaceFormList = iAppInterfaceService.getRetAppInterface(iAppInterfaceForm.getGuid());

           for (IAppInterfaceForm iAppInterface : iAppInterfaceFormList) {
                //打印结果通知接口
                callOut_invPrintRetInfoOutController.invOpenRetInfoOutController(iAppInterface,pInvoiceBlue,pInvoiceRed);
              }
        } catch (BopException e) {
            e.printStackTrace();
            log.info("访问失败");
            log.info(e.getErrCode());
            log.info(e.getErrMsg());
            log.info(e.getMessage());
            retJson.setErrorCode(e.getErrCode());
            retJson.setErrorMessage(e.getSubMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("打印结果通知失败");
            retJson.setErrorCode("1110");
            retJson.setErrorMessage("打印结果通知外部系统失败!");
        }
        return retJson;
    }
}
